package com.sphd.beautysalon.activitys;

import android.app.TimePickerDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.TimePicker;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.bigkoo.pickerview.OptionsPickerView;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.sphd.beautysalon.R;
import com.sphd.beautysalon.base.BaseActivity;
import com.sphd.beautysalon.base.RestaurantUrl;
import com.sphd.beautysalon.info.LoginInfo;
import com.sphd.beautysalon.info.RestaurantInfo;
import com.sphd.beautysalon.presenter.RestaurantPresenterImpl;
import com.sphd.beautysalon.utils.Constant;
import com.sphd.beautysalon.utils.JsonFileReader;
import com.sphd.beautysalon.view.RestaurantView;
import com.wzh.frame.utils.StringUtils;
import com.wzh.frame.utils.image.LocalImageDo;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 店铺信息
 */
public class RestaurantActivity extends BaseActivity implements GeocodeSearch.OnGeocodeSearchListener, RestaurantView {

    @BindView(R.id.now_adr)
    ImageView nowAdr;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.restaurant_city)
    TextView restaurantCity;
    @BindView(R.id.restaurant_name)
    MaterialEditText restaurantName;
    @BindView(R.id.restaurant_address)
    MaterialEditText restaurantAddress;
    @BindView(R.id.restaurant_adr_auto)
    MaterialEditText restaurantAdrAuto;
    @BindView(R.id.restaurant_tel)
    MaterialEditText restaurantTel;
    @BindView(R.id.open_time_textview)
    TextView openTimeTextview;
    @BindView(R.id.close_time_textview)
    TextView closeTimeTextview;
    @BindView(R.id.restaurant_time_linear)
    LinearLayout restaurantTimeLinear;
    @BindView(R.id.restaurant_photo_textview)
    TextView restaurantPhotoTextview;
    @BindView(R.id.restaurant_img)
    ImageView restaurantImg;
    @BindView(R.id.update)
    Button update;
    @BindView(R.id.content_restaurant)
    NestedScrollView contentRestaurant;
    Intent intent;
    Bundle bundle;
    RestaurantInfo restaurantInfo;
    @BindView(R.id.restaurant_address_now)
    MaterialEditText restaurantAddressNow;
    private Double cg_lng = 0d;
    private Double cg_lat = 0d;
    //定义显示时间控件
    private Calendar calendar; //通过Calendar获取系统时间
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = new AMapLocationClientOption();
    OptionsPickerView pvOptions;
    private static final int TAKEPHOTO = 100;
    private static final int LOCATIONPHOTO = 101;
    private static final int ZOOMRESOULT = 102;
    private Uri imageUri;
    private Uri imageCropUri;
    File file;//原图文件
    File cropFile;//裁切图文件
    boolean isFinish = false;
    RestaurantPresenterImpl restaurantPresenter;
    //  省份
//    ArrayList<ProvinceBean> provinceBeanList = new ArrayList<>();


    //  城市
    ArrayList<String> provinces = new ArrayList<>();
//    ArrayList<List<String>> provincesList = new ArrayList<>();

    //  城市
    ArrayList<String> cities;
    ArrayList<List<String>> cityList = new ArrayList<>();
    //  区/县
    ArrayList<String> district;
    ArrayList<List<String>> districts;
    ArrayList<List<List<String>>> districtList = new ArrayList<>();
    private String cgName, cgAddr, cgPhone, openSt, openEt, image;
    LoginInfo loginInfo;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_restaurant);
        ButterKnife.bind(this);
        initView();
        initCityJson();
        initImage();
        initEvent();
    }

    private void initImage() {
        String path = getSDCardPath();
        file = new File(path + "/temp.jpg");
        imageUri = Uri.fromFile(file);
        cropFile = new File(getSDCardPath() + "/temp_crop.jpg");
        imageCropUri = Uri.fromFile(cropFile);
    }

    private void initCityJson() {
        //  创建选项选择器
        pvOptions = new OptionsPickerView(this);
        //  获取json数据
        String province_data_json = JsonFileReader.getJson(this, "province_data.json");
        //  解析json数据
        parseJson(province_data_json);
        //  设置三级联动效果
        pvOptions.setPicker(provinces, cityList, districtList, true);

        //  设置选择的三级单位
        //pvOptions.setLabels("省", "市", "区");
        //pvOptions.setTitle("选择城市");

        //  设置是否循环滚动
        pvOptions.setCyclic(false, false, false);


        // 设置默认选中的三级项目
        pvOptions.setSelectOptions(0, 0, 0);
        //  监听确定选择按钮
        pvOptions.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                //返回的分别是三个级别的选中位置
//                String city = provinceBeanList.get(options1).getPickerViewText();
                String city = provinces.get(options1);
                String address;
                //  如果是直辖市或者特别行政区只设置市和区/县
                if ("北京市".equals(city) || "上海市".equals(city) || "天津市".equals(city) || "重庆市".equals(city) || "澳门".equals(city) || "香港".equals(city)) {
//                    address = city
//                            + " " + districtList.get(options1).get(option2).get(options3);
                    address = provinces.get(options1);
                } else {
                    address = cityList.get(options1).get(option2);
                }
                restaurantCity.setText(address);
            }
        });
    }

    private void initEvent() {
            toolbar.setNavigationOnClickListener(v -> {
                finish();
            });
    }

    private void initView() {
        setTitleBar(toolbar, "店铺信息");
        intent = getIntent();
        bundle = intent.getExtras();
        restaurantInfo = (RestaurantInfo) bundle.getSerializable(Constant.RESTAURANTSINFO);
        calendar = Calendar.getInstance();
        restaurantPresenter=new RestaurantPresenterImpl(this);
        loginInfo= DataSupport.findLast(LoginInfo.class);
        if (restaurantInfo.getStaff_status()==1 && loginInfo.getStaff_auth() == 2) {
            update.setVisibility(View.GONE);
        }
        setRetaurant();
        initLocation();
    }

    private void setRetaurant() {
        restaurantName.setText(restaurantInfo.getCg_name());
        restaurantAddress.setText(restaurantInfo.getCg_addr());
        restaurantTel.setText(restaurantInfo.getCg_phone());
        openTimeTextview.setText(restaurantInfo.getCg_openst() == null ? "00:00" : restaurantInfo.getCg_openst());
        closeTimeTextview.setText(restaurantInfo.getCg_openet() == null ? "00:00" : restaurantInfo.getCg_openet());
        restaurantCity.setText(restaurantInfo.getCg_city());
        if (restaurantInfo.getCg_pic() != null) {
            setImage(restaurantImg, restaurantInfo.getCg_pic());
        } else {
            restaurantImg.setImageResource(R.mipmap.moren);
        }
        cg_lng = restaurantInfo.getCg_lng();
        cg_lat = restaurantInfo.getCg_lat();
    }

    /**
     * 初始化定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void initLocation() {
        //初始化client
        locationClient = new AMapLocationClient(this.getApplicationContext());
        //设置定位参数
        locationClient.setLocationOption(getDefaultOption());
        // 设置定位监听
        locationClient.setLocationListener(locationListener);
    }

    /**
     * 默认的定位参数
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private AMapLocationClientOption getDefaultOption() {
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.setInterval(2000);//可选，设置定位间隔。默认为2秒
        mOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        mOption.setOnceLocation(false);//可选，设置是否单次定位。默认是false
        mOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        mOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
        mOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
        return mOption;
    }

    /**
     * 定位监听
     */
    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation loc) {
            if (null != loc && loc.getErrorCode() == 0) {
                //解析定位结果
                toast("定位成功");
//                restaurantAddressNow.setVisibility(View.VISIBLE);
                restaurantCity.setText(loc.getCity());
                cg_lat = loc.getLatitude();
                cg_lng = loc.getLongitude();
                restaurantAddress.setText(loc.getAddress());

            } else {
                toast("定位失败,请手动输入地址。");
            }
            stopLocation();
        }
    };
    public static String getSDCardPath() {
        String cmd = "cat /proc/mounts";
        Runtime run = Runtime.getRuntime();// 返回与当前 Java 应用程序相关的运行时对象
        try {
            Process p = run.exec(cmd);// 启动另一个进程来执行命令
            BufferedInputStream in = new BufferedInputStream(p.getInputStream());
            BufferedReader inBr = new BufferedReader(new InputStreamReader(in));

            String lineStr;
            while ((lineStr = inBr.readLine()) != null) {
                // 获得命令执行后在控制台的输出信息
                if (lineStr.contains("sdcard")
                        && lineStr.contains(".android_secure")) {
                    String[] strArray = lineStr.split(" ");
                    if (strArray != null && strArray.length >= 5) {
                        String result = strArray[1].replace("/.android_secure",
                                "");
                        return result;
                    }
                }
                // 检查命令是否执行失败。
                if (p.waitFor() != 0 && p.exitValue() == 1) {
                    // p.exitValue()==0表示正常结束，1：非正常结束
                }
            }
            inBr.close();
            in.close();
        } catch (Exception e) {

            return Environment.getExternalStorageDirectory().getPath();
        }

        return Environment.getExternalStorageDirectory().getPath();
    }
    /**
     * 开始定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void startLocation() {
        //根据控件的选择，重新设置定位参数

        // 设置定位参数
        locationClient.setLocationOption(locationOption);
        // 启动定位
        locationClient.startLocation();
    }

    /**
     * 停止定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void stopLocation() {
        // 停止定位
        locationClient.stopLocation();
    }

    /**
     * 销毁定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void destroyLocation() {
        if (null != locationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
    }


    @OnClick({R.id.now_adr, R.id.update, R.id.restaurant_city,
            R.id.open_time_textview, R.id.close_time_textview,
    R.id.restaurant_img})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.now_adr:
                //初始化定位
                startLocation();
                break;
            case R.id.update:
                checkNull();
                break;
            case R.id.restaurant_city:
                pvOptions.show();
                break;
            case R.id.open_time_textview:
                showText(openTimeTextview);
                break;
            case R.id.close_time_textview:
                showText(closeTimeTextview);
                break;
            case R.id.restaurant_img:
                LocalImageDo localImageDo = new LocalImageDo(contentRestaurant, this);
                localImageDo.setOnClickButtonListener(new LocalImageDo.OnClickButtonListener() {
                    @Override
                    public void OnClick(View view, PopupWindow popupWindow) {
                        if (view.getId() == R.id.camara) {
                            takePhoto();
                        } else if (view.getId() == R.id.photo) {
                            chooseFromGallery();
                        }
                        popupWindow.dismiss();
                    }
                });
                localImageDo.showPopuWindow();
                break;
        }
    }

    /**
     * 从相册选择图片
     */
    private void chooseFromGallery() {
        //构建一个内容选择的Intent
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, LOCATIONPHOTO);
    }

    /**
     * 打开相机的时候确定此张图片的名字
     */
    private void takePhoto() {
        Intent intent = null;
        intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//action is capture
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, TAKEPHOTO);

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == TAKEPHOTO) {
            cropImg(imageUri);
        } else if (requestCode == LOCATIONPHOTO) {
            if (data == null) {
                return;
            } else {
                //获取到用户所选图片的Uri
                imageUri = data.getData();
                cropImg(imageUri);
            }

        } else if (requestCode == ZOOMRESOULT) {
            Bundle extras = data.getExtras();
            if (extras != null) {
                try {
                    Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageCropUri));
                    restaurantImg.setImageBitmap(bitmap);
                    isFinish = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void cropImg(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 700);
        intent.putExtra("outputY", 700);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageCropUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, ZOOMRESOULT);
    }



    private void checkNull() {
        if (StringUtils.isEmpty(restaurantName.getText())) {
            restaurantName.setError("餐馆名称为空");
        } else {
            if (StringUtils.isEmpty(restaurantCity.getText())) {
                toast("请选择或定位城市");
            } else {
                if (StringUtils.isEmpty(restaurantAddress.getText())) {
                    toast("请输入地址或定位当前位置");
                } else {
                    if (StringUtils.isEmpty(restaurantPhotoTextview.getText())) {
                        toast("请输入电话号码");
                    } else {
                        //将地址转换成坐标
                        getLotLat(restaurantAddress.getText().toString(),restaurantCity.getText().toString());

                    }
                }
            }
        }


    }

    private void getLotLat(String address, String city) {
        //构造 GeocodeSearch 对象，并设置监听。
        GeocodeSearch geocodeSearch = new GeocodeSearch(this);
        geocodeSearch.setOnGeocodeSearchListener(this);
//通过GeocodeQuery设置查询参数,调用getFromLocationNameAsyn(GeocodeQuery geocodeQuery) 方法发起请求。
//address表示地址，第二个参数表示查询城市，中文或者中文全拼，citycode、adcode都ok
        GeocodeQuery query = new GeocodeQuery(address, city);
        geocodeSearch.getFromLocationNameAsyn(query);
    }


    private void showText(TextView textView) {
        new TimePickerDialog(context,
                new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hour, int minute) {
                        // TODO Auto-generated method stub
                        //更新EditText控件时间 小于10加0

                        textView.setText(new StringBuilder()
                                .append(hour < 10 ? "0" + hour : hour).append(":")
                                .append(minute < 10 ? "0" + minute : minute));
                    }
                }, calendar.get(Calendar.HOUR_OF_DAY),
                calendar.get(Calendar.MINUTE), true).show();
    }

    //  解析json填充集合
    public void parseJson(String str) {
        try {
            //  获取json中的数组
            JSONArray jsonArray = new JSONArray(str);
            //  遍历数据组
            for (int i = 0; i < jsonArray.length(); i++) {
                //  获取省份的对象
                JSONObject provinceObject = jsonArray.optJSONObject(i);
                //  获取省份名称放入集合
                String provinceName = provinceObject.getString("name");
//                provinceBeanList.add(new ProvinceBean(provinceName));
                provinces.add(provinceName);
                //  获取城市数组
                JSONArray cityArray = provinceObject.optJSONArray("city");
                cities = new ArrayList<>();//   声明存放城市的集合
                districts = new ArrayList<>();//声明存放区县集合的集合
                //  遍历城市数组
                for (int j = 0; j < cityArray.length(); j++) {
                    //  获取城市对象
                    JSONObject cityObject = cityArray.optJSONObject(j);
                    //  将城市放入集合
                    String cityName = cityObject.optString("name");
                    cities.add(cityName);
                    district = new ArrayList<>();// 声明存放区县的集合
                    //  获取区县的数组
                    JSONArray areaArray = cityObject.optJSONArray("area");
                    //  遍历区县数组，获取到区县名称并放入集合
                    for (int k = 0; k < areaArray.length(); k++) {
                        String areaName = areaArray.getString(k);
                        district.add(areaName);
                    }
                    //  将区县的集合放入集合
                    districts.add(district);
                }
                //  将存放区县集合的集合放入集合
                districtList.add(districts);
                //  将存放城市的集合放入集合
                cityList.add(cities);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }



    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
        Log.e("000===","0000");
    }

    @Override
    public void onGeocodeSearched(GeocodeResult result, int rCode) {
        if (rCode == 1000) {
            if (result != null && result.getGeocodeAddressList() != null
                    && result.getGeocodeAddressList().size() > 0) {
                GeocodeAddress address = result.getGeocodeAddressList().get(0);
                LatLonPoint latLonPoint=address.getLatLonPoint();
                cg_lat=latLonPoint.getLatitude();
                cg_lng=latLonPoint.getLongitude();
                Log.e("1111===",cg_lat+"/////0000//////"+cg_lng);
            } else {
                toast("暂时无法获取到相应的位置。");
            }
        } else {
            toast(rCode+"");
        }
        //在此位置进行上传
        goNet();
    }

    private void goNet() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("cg_name", restaurantName.getText().toString().trim());
        map.put("cg_addr", restaurantAddress.getText().toString().trim());
        map.put("cg_phone", restaurantTel.getText().toString().trim());
        map.put("cg_openst", openTimeTextview.getText().toString().trim());
        map.put("cg_openet", closeTimeTextview.getText().toString().trim());
        map.put("cg_city", restaurantCity.getText().toString().trim());
        map.put("cg_lng", "" + cg_lng);
        map.put("cg_lat", "" + cg_lat);
        map.put("id", "" + restaurantInfo.getId());
        List<File> fileList = new ArrayList<>();
        fileList.add(cropFile);
        if (isFinish) {
            restaurantPresenter.sendUp(RestaurantUrl.Httptitle + RestaurantUrl.ChangeRestaurant,"image", fileList, map);
        } else {
           restaurantPresenter.sendUpNoImage(RestaurantUrl.Httptitle + RestaurantUrl.ChangeRestaurant,map);
        }
    }

    @Override
    public void recRes(int res) {

        if (res==1){
            toast("提交成功");
            setResult(1);
            finish();
        }else {
            toast("提交失败，请重试！");

        }
    }

    @Override
    public void showLoading() {
        showLoadingDialog();
    }

    @Override
    public void dissLoading() {
        dissLoadingDialog();
    }
}
